// improved-sse-client.js
// 改进的SSE客户端，用于替换Chat.vue中的SSE连接处理

export class ImprovedSSEClient {
    constructor() {
        this.eventSource = null;
        this.connectionState = 'disconnected'; // disconnected, connecting, connected, error
        this.retryCount = 0;
        this.maxRetries = 3;
        this.retryDelay = 1000; // 1秒
        this.isManuallyClosing = false;
    }

    /**
     * 发送文本消息并建立SSE连接
     */
    async sendMessage(conversationId, content, callbacks = {}) {
        try {
            // 如果已有连接，先关闭
            this.closeConnection();

            this.connectionState = 'connecting';
            this.isManuallyClosing = false;

            // 构建请求URL
            const url = new URL('/ai/conversation/message/text', 'http://localhost:8088');
            url.searchParams.append('conversationId', conversationId);
            url.searchParams.append('content', content);

            // 创建SSE连接
            this.eventSource = new EventSource(url.toString());

            // 设置事件监听器
            this.setupEventListeners(callbacks);

            return new Promise((resolve, reject) => {
                // 连接成功回调
                this.eventSource.onopen = () => {
                    console.log('SSE连接已建立');
                    this.connectionState = 'connected';
                    this.retryCount = 0;
                    if (callbacks.onOpen) callbacks.onOpen();
                };

                // 连接错误回调
                this.eventSource.onerror = (error) => {
                    console.warn('SSE连接发生错误:', error);
                    this.connectionState = 'error';
                    
                    if (this.isManuallyClosing) {
                        // 如果是手动关闭，不进行重试
                        resolve({ success: true, message: '连接已手动关闭' });
                        return;
                    }

                    if (callbacks.onError) {
                        callbacks.onError(error);
                    }

                    // 自动重试机制
                    this.handleConnectionError(reject);
                };

                // 设置超时处理
                setTimeout(() => {
                    if (this.connectionState === 'connecting') {
                        console.warn('SSE连接超时');
                        this.closeConnection();
                        reject(new Error('连接超时'));
                    }
                }, 10000); // 10秒超时
            });

        } catch (error) {
            console.error('发送SSE消息失败:', error);
            this.connectionState = 'error';
            throw error;
        }
    }

    /**
     * 设置SSE事件监听器
     */
    setupEventListeners(callbacks) {
        if (!this.eventSource) return;

        // 文本块事件
        this.eventSource.addEventListener('text_chunk', (event) => {
            try {
                const data = JSON.parse(event.data);
                if (callbacks.onTextChunk) {
                    callbacks.onTextChunk(data.chunk, data);
                }
            } catch (error) {
                console.error('解析text_chunk事件失败:', error);
            }
        });

        // 完成事件
        this.eventSource.addEventListener('complete', (event) => {
            try {
                const data = JSON.parse(event.data);
                console.log('AI响应完成:', data);
                if (callbacks.onComplete) {
                    callbacks.onComplete(data);
                }
                // 响应完成后关闭连接
                this.closeConnection();
            } catch (error) {
                console.error('解析complete事件失败:', error);
            }
        });

        // 错误事件
        this.eventSource.addEventListener('error', (event) => {
            try {
                const data = JSON.parse(event.data);
                console.error('服务器错误:', data.error);
                if (callbacks.onServerError) {
                    callbacks.onServerError(data.error);
                }
            } catch (error) {
                console.error('解析error事件失败:', error);
            }
        });

        // 对话创建事件
        this.eventSource.addEventListener('conversation_created', (event) => {
            try {
                const data = JSON.parse(event.data);
                console.log('对话创建成功:', data);
                if (callbacks.onConversationCreated) {
                    callbacks.onConversationCreated(data);
                }
            } catch (error) {
                console.error('解析conversation_created事件失败:', error);
            }
        });
    }

    /**
     * 处理连接错误和重试
     */
    handleConnectionError(rejectCallback) {
        if (this.retryCount < this.maxRetries && !this.isManuallyClosing) {
            this.retryCount++;
            console.log(`SSE连接重试 ${this.retryCount}/${this.maxRetries}`);
            
            setTimeout(() => {
                if (!this.isManuallyClosing) {
                    // 重新建立连接的逻辑需要在调用方实现
                    console.log('准备重试SSE连接...');
                }
            }, this.retryDelay * this.retryCount);
        } else {
            console.error('SSE连接重试次数已用完');
            if (rejectCallback) {
                rejectCallback(new Error('连接失败，重试次数已用完'));
            }
        }
    }

    /**
     * 手动关闭连接
     */
    closeConnection() {
        if (this.eventSource) {
            this.isManuallyClosing = true;
            this.eventSource.close();
            this.eventSource = null;
            this.connectionState = 'disconnected';
            console.log('SSE连接已手动关闭');
        }
    }

    /**
     * 获取连接状态
     */
    getConnectionState() {
        return this.connectionState;
    }

    /**
     * 检查连接是否活跃
     */
    isConnected() {
        return this.connectionState === 'connected' && 
               this.eventSource && 
               this.eventSource.readyState === EventSource.OPEN;
    }
}

// 使用示例（在Chat.vue中使用）:
/*
import { ImprovedSSEClient } from './improved-sse-client.js';

export default {
    data() {
        return {
            sseClient: new ImprovedSSEClient(),
            currentMessage: '',
            isReceiving: false
        }
    },
    
    methods: {
        async sendMessage(content) {
            try {
                this.isReceiving = true;
                this.currentMessage = '';
                
                await this.sseClient.sendMessage(this.conversationId, content, {
                    onOpen: () => {
                        console.log('开始接收AI响应...');
                    },
                    
                    onTextChunk: (chunk) => {
                        this.currentMessage += chunk;
                        // 触发界面更新
                        this.$forceUpdate();
                    },
                    
                    onComplete: (data) => {
                        console.log('AI响应完成');
                        this.isReceiving = false;
                        // 可以在这里触发其他操作，如保存到历史记录
                    },
                    
                    onError: (error) => {
                        console.error('连接错误:', error);
                        this.isReceiving = false;
                        // 显示错误提示给用户
                    },
                    
                    onServerError: (errorMessage) => {
                        console.error('服务器错误:', errorMessage);
                        this.isReceiving = false;
                        // 显示服务器错误给用户
                    }
                });
                
            } catch (error) {
                console.error('发送消息失败:', error);
                this.isReceiving = false;
                // 显示错误提示
            }
        }
    },
    
    beforeUnmount() {
        // 组件销毁时关闭连接
        if (this.sseClient) {
            this.sseClient.closeConnection();
        }
    }
}
*/
